package org.jactao.rpc;

import org.jactao.cluster.LClusterInvoker;
import org.jactao.common.LException;
import org.jactao.common.LReferConfig;
import org.jactao.common.LRequest;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * Created by fanzetao on 2018/4/4.
 */
public class LProxy implements InvocationHandler {

    private LInvoker invoker;

    private LReferConfig referConfig;

    public LProxy(LReferConfig referConfig) {
        this.referConfig = referConfig;
        invoker = new LClusterInvoker(referConfig);
    }

    private void checkRequired() {
        if(referConfig == null)
            throw new LException("referConfig not null");
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        checkRequired();

        LRequest request = new LRequest();
        request.setRequestId(LRequest.rid.incrementAndGet());
        request.setClazz(referConfig.getInterfaceClass());
        request.setMethod(method.getName());
        request.setParameterTypes(method.getParameterTypes());
        request.setParams(args);
        request.setVersion(referConfig.getVersion());
        return invoker.invoke(request).getResponse();
    }

}
